<template>
  <div class="components-container main-container">
    <el-row>
      <el-steps :active="active"  align-center>
        <el-step title="步骤 1" description="发布考勤信息" icon="el-icon-edit"></el-step>
        <el-step title="步骤 2" description="通知学生考勤" icon="el-icon-upload"></el-step>
        <el-step title="步骤 3" description="系统自动关闭任务" icon="el-icon-picture"></el-step>
      </el-steps>
    </el-row>
    <el-row style="margin-top: 50px;margin-left: 100px;">
      <textarea style="margin-top: 20%" id="tinymceId" v-model="attendance.content" />
    </el-row>
    <el-row style="margin-top: 50px;margin-left: 100px;">
      <el-col :span="24">
        <el-form ref="attengance_form" :label-position="'top'" :rules="rules" :model="attendance" class="demo-form-inline">
          <el-form-item label="ip白名单" prop="ip">
            <el-input v-model="attendance.ip" placeholder="ip地址"></el-input>
          </el-form-item>
          <el-form-item label="选择课程" prop="course">
            <el-select v-model="attendance.course" placeholder="选择课程">
              <el-option
                v-for="item in courses"
                :key="item.courseNo"
                :label="item.courseName"
                :value="item.courseNo">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="考勤时间" prop="startTime">
            <el-date-picker
              v-model="attendance.startTime"
              type="datetime"
              placeholder="选择考勤时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="迟到允许时间" prop="allow_time">
            <el-input v-model="attendance.allow_time" placeholder="迟到允许时间"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="save">发布</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import load from '../rich-editor/tinymce-components/dynamicLoadScript'
  import toolbar from '../rich-editor/tinymce-components/toolbar'
  import plugins from '../rich-editor/tinymce-components/plugins'

  // why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
  const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'
  function checkIp(rule, value, callback){
    var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
    let ips=value.split(";");
    let res=true;
    for (let i = 0; i <ips.length ; i++) {
      res=reg.test(ips[i]);
    }
    if (!res){
      return  callback(new Error('多个ip地址必须以;隔开，且格式要正确'));
    }else{
      return callback();
    }
  }
  function checkAllowTime(rule,value,callback) {
    var reg=/^[0-9]$/g;
    if (!reg.test(value)){
      return  callback(new Error('时间必须是数字，且最大不得超过十分钟'))
    }else{
      return callback();
    }

  }
  function checkStartTime(rule,value,callback) {
    let date=new Date();
    if (value<date){
      return callback(new Error("不得早于当前时间"));
    }else{
      return callback();
    }
  }
  export default {
    name: 'Publish',
    data() {
      return {
        courses:[],
        active:0,// 进度条
        hasChange: false,
        hasInit: false,
        tinymceId: 'tinymceId',
        height: 360,
        toolbar: [],
        menubar: 'file edit insert view format table',
        languageTypeList: {
          'en': 'en',
          'zh': 'zh_CN'
        },
        attendance:{user:'',course:'',startTime:'',ip:'',allow_time:'',
          course:[],
          content: '<h1 style="text-align: center;">填写考勤事由</h1><p style="text-align: center; font-size: 15px;"><a href="//shang.qq.com/wpa/qunwpa?idkey=32da7a18744756b0d8ffdd05b84999afecb5265dbad0fb119033e122abe803f3" target="_blank" rel="noopener"><img title="TinyMCE Logo" src="https://raw.githubusercontent.com/Neveryu/prerender-website/master/src/assets/logo1.png" alt="TinyMCE Logo" width="120" /></a></p><p>请书写你的内容</p>',},
        // 富文本内容
        rules: {
          course: [
            { required: true, message: '请选择课程', trigger: 'change' }
          ],
          startTime: [
            { type: 'date', required: true, message: '请选择有效时间', trigger: 'change',validator:checkStartTime }
          ],
          ip: [
            { required: true, message: '请输入合法ip地址', trigger: 'change',validator:checkIp }
          ],
          allow_time: [
            {  required: true,validator:checkAllowTime, message: '请输入允许迟到时间差,最长不得超过10分钟', trigger: 'change' }
          ],
        }
      }
    },
    watch: {
      content(val) {
        if (!this.hasChange && this.hasInit) {
          this.$nextTick(() => window.tinymce.get(this.tinymceId).setContent(val || ''))
        }
      }
    },
    methods: {
      init() {
        // dynamic load tinymce from cdn
        load(tinymceCDN, (err) => {
          if (err) {
            this.$message.error(err.message)
            return
          }
          this.initTinymce()
        })
      },
      initTinymce() {
        const _this = this
        window.tinymce.init({
          selector: `#${this.tinymceId}`,
          language: this.languageTypeList['zh'],
          height: this.height,
          body_class: 'panel-body ',
          object_resizing: false,
          toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
          plugins,
          width:723,
          height:300,
          menubar: this.menubar,
          end_container_on_empty_block: true,
          powerpaste_word_import: 'clean',
          code_dialog_height: 100,
          code_dialog_width: 1000,
          advlist_bullet_styles: 'square',
          advlist_number_styles: 'default',
          imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
          default_link_target: '_blank',
          link_title: false,
          nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
          init_instance_callback: editor => {
            if (_this.content) {
              editor.setContent(_this.content)
            }
            _this.hasInit = true
            editor.on('NodeChange Change KeyUp SetContent', () => {
              this.hasChange = true
              this.content = editor.getContent()
            })
          },
          setup(editor) {
            editor.on('FullscreenStateChanged', (e) => {
              _this.fullscreen = e.state
            })
          }
        })
      },
      destroyTinymce() {
        const tinymce = window.tinymce.get(this.tinymceId)
        if (this.fullscreen) {
          tinymce.execCommand('mceFullScreen')
        }
        if (tinymce) {
          tinymce.destroy()
        }
      },
      //保存
      save(){
        debugger
        let g=this;
        let attendance_parent={courseNo:'',publishNo:this.$store.getters.userId,attendanceExpectStartTime:'',allowTimeDifference:''
        ,whiteIpv4Address:'',content:''};
        this.$refs.attengance_form.validate(valid=>{
          console.log(valid)
          if (valid){
            g.$set(attendance_parent,'courseNo',g.attendance.course);
            g.$set(attendance_parent,'attendanceExpectStartTime',g.attendance.startTime.getTime());
            g.$set(attendance_parent,'allowTimeDifference',new Date(g.attendance.startTime.getTime()+(parseInt(g.attendance.allow_time))*60*1000).getTime());
            g.$set(attendance_parent,'whiteIpv4Address',g.attendance.ip);
            g.$set(attendance_parent,'content',g.attendance.content);
            g.$ajaxPost('/attendanceParent/publish',attendance_parent).then(res=>{
              g.message({type:'success',message:`发布成功`})
              g.active=1;
            }).catch(e=>{

            })
          }else{

          }
        })

      },
      loadCourses(){
        let g=this;
        g.attendance.course=[];
        g.$ajaxGet('/course/all',{teacherId:g.$store.getters.userId}).then(res=>{
         g.courses=res;
        })

      }
    },
    created(){
      this.loadCourses();
    },
    mounted() {
      this.init()
    },
    beforeDestroy() {
      this.destroyTinymce()
    },
    activated() {
      if(window.tinymce) {
        this.initTinymce()
      }
    },
    deactivated() {
      this.destroyTinymce()
    }
  }
</script>

<style scoped>
  .main-container {
    max-width: 80%;
    min-width: 800px;
  }
  .tinymce-container {
    position: relative;
    line-height: normal;
  }
  .tinymce-container>>>.mce-fullscreen {
    z-index: 10000;
  }
  .tinymce-textarea {
    visibility: hidden;
    z-index: -1;
  }
</style>
